const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 确保上传目录存在
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
}

// 配置 multer 存储
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const siteId = req.body.siteId || uuidv4().slice(0, 8);
        const siteDir = path.join(uploadsDir, siteId);
        
        if (!fs.existsSync(siteDir)) {
            fs.mkdirSync(siteDir, { recursive: true });
        }
        
        cb(null, siteDir);
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});

const upload = multer({ 
    storage: storage,
    fileFilter: function (req, file, cb) {
        // 允许所有文件类型
        cb(null, true);
    }
});

// 上传接口
app.post('/upload', upload.array('files'), (req, res) => {
    try {
        const siteId = req.body.siteId || uuidv4().slice(0, 8);
        const customDomain = req.body.customDomain || '';
        
        const siteUrl = customDomain 
            ? `http://localhost:${PORT}/${customDomain}`
            : `http://localhost:${PORT}/${siteId}`;
        
        res.json({
            success: true,
            siteId: siteId,
            url: siteUrl,
            files: req.files.map(file => ({
                name: file.originalname,
                size: file.size,
                path: file.path
            }))
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

// 托管静态文件
app.use('/:siteId', (req, res, next) => {
    const siteId = req.params.siteId;
    const siteDir = path.join(uploadsDir, siteId);
    
    if (fs.existsSync(siteDir)) {
        express.static(siteDir)(req, res, next);
    } else {
        // 检查是否是自定义域名
        const customDirs = fs.readdirSync(uploadsDir);
        for (const dir of customDirs) {
            const configPath = path.join(uploadsDir, dir, 'config.json');
            if (fs.existsSync(configPath)) {
                const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
                if (config.customDomain === siteId) {
                    express.static(path.join(uploadsDir, dir))(req, res, next);
                    return;
                }
            }
        }
        
        res.status(404).send('站点不存在');
    }
});

// 创建自定义域名配置
app.post('/custom-domain', (req, res) => {
    const { siteId, customDomain } = req.body;
    
    if (!siteId || !customDomain) {
        return res.status(400).json({
            success: false,
            error: '缺少必要参数'
        });
    }
    
    const siteDir = path.join(uploadsDir, siteId);
    const configPath = path.join(siteDir, 'config.json');
    
    fs.writeFileSync(configPath, JSON.stringify({ customDomain }));
    
    res.json({
        success: true,
        url: `http://localhost:${PORT}/${customDomain}`
    });
});

// 获取站点列表
app.get('/sites', (req, res) => {
    try {
        const sites = fs.readdirSync(uploadsDir)
            .filter(dir => fs.statSync(path.join(uploadsDir, dir)).isDirectory())
            .map(dir => {
                const configPath = path.join(uploadsDir, dir, 'config.json');
                let customDomain = null;
                
                if (fs.existsSync(configPath)) {
                    const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
                    customDomain = config.customDomain;
                }
                
                return {
                    id: dir,
                    url: customDomain 
                        ? `http://localhost:${PORT}/${customDomain}`
                        : `http://localhost:${PORT}/${dir}`,
                    customDomain: customDomain,
                    createdAt: fs.statSync(path.join(uploadsDir, dir)).birthtime
                };
            });
        
        res.json(sites);
    } catch (error) {
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

// 删除站点
app.delete('/sites/:siteId', (req, res) => {
    const siteId = req.params.siteId;
    const siteDir = path.join(uploadsDir, siteId);
    
    if (fs.existsSync(siteDir)) {
        fs.rmSync(siteDir, { recursive: true, force: true });
        res.json({ success: true });
    } else {
        res.status(404).json({
            success: false,
            error: '站点不存在'
        });
    }
});

app.listen(PORT, () => {
    console.log(`静态网页托管平台运行在 http://localhost:${PORT}`);
});
